<template>
  <div class="qus-table-container">
    <table class="qus-table">
      <thead>
        <tr>
          <th  style="border-right: 1px solid #fff;width: 70px;font-size: 20px;text-align: center;">{{ t('game.questionTable.serialNumber') }}</th>
          <th  style="border-right: 1px solid #fff;font-size: 20px;text-align: center;">{{ t('game.questionTable.assessmentContent') }}</th>
          <th style="font-size: 20px;text-align: center;width: 100px;">{{ t('game.questionTable.score') }}</th>
        </tr>
      </thead>
      <tbody style="overflow-y: auto;">
        <template v-for="(type, typeIdx) in infoData.questionTypeList" :key="'type-'+typeIdx">
        <!-- 调试信息 -->
        <tr v-if="!type.questionType || type.questionType.trim() === ''" style="background: #ffcccc;">
          <!-- <td colspan="3" style="text-align: center; color: red;">
            调试: 第{{ typeIdx + 1 }}级 questionType="{{type.questionType}}" keys={{Object.keys(type).join(',')}}
          </td> -->
        </tr>
        <template v-if="type && (type.questionType || type.questionList)" >
          <tr 
            :class="{
              selected: selectedIndex === String(typeIdx),
              hovered: hoverIndex === String(typeIdx),
              current: currentIndex[0] === typeIdx && currentIndex[1] === -1
            }"
            :data-debug="`main:${currentIndex[0]}-${currentIndex[1]}|${typeIdx}`"
            @click="selectRow(String(typeIdx),undefined,undefined)"
            @mouseenter="hoverIndex = String(typeIdx)"
            @mouseleave="hoverIndex = ''">
            <td  style="text-align: center;width: 70px;">{{ typeIdx + 1 }}</td>
            <td style="padding-left: 10px;">{{ type.questionType || t('game.questionTable.question', { number: typeIdx + 1 }) }}</td>
            <td style="text-align: center;width:93px;">
              <!-- 一级大题不显示分数 -->
            </td>
          </tr>
        </template>
          <template v-for="(item, itemIdx) in type.questionList" :key="'item-'+typeIdx+'-'+itemIdx">
            <!-- 有第三级子题的情况 -->
            <template v-if="item.questionList && item.questionList.length > 0">
              <!-- 二级题目标题 -->
              <tr v-if="item.title"
                :class="{
                  selected: selectedIndex === typeIdx+'-'+itemIdx,
                  hovered: hoverIndex === typeIdx+'-'+itemIdx,
                  current: currentIndex[0] === typeIdx && currentIndex[1] === itemIdx && (currentIndex[2] === undefined || currentIndex[2] === -1)
                }"
                :data-debug="`sub:${currentIndex[0]}-${currentIndex[1]}-${currentIndex[2] || -1}|${typeIdx}-${itemIdx}`"
                @click="selectRow(typeIdx,itemIdx,undefined)"
                @mouseenter="hoverIndex = typeIdx+'-'+itemIdx"
                @mouseleave="hoverIndex = ''">
                <td style="text-align: center;width: 70px;">{{ typeIdx + 1 }}.{{ itemIdx + 1 }}</td>
                <td style="padding-left: 30px;">{{ item.title }}</td>
                <td style="text-align: center;width: 93px;">
                  <!-- 有三级子题时，二级题目不显示分数 -->
                </td>
              </tr>
              <!-- 三级子题 -->
              <template v-for="(subItem, subIdx) in item.questionList" :key="'subitem-'+typeIdx+'-'+itemIdx+'-'+subIdx">
                <tr v-if="subItem.title"
                  :class="{
                    selected: selectedIndex === typeIdx+'-'+itemIdx+'-'+subIdx,
                    hovered: hoverIndex === typeIdx+'-'+itemIdx+'-'+subIdx,
                    current: currentIndex[0] === typeIdx && currentIndex[1] === itemIdx && currentIndex[2] === subIdx
                  }"
                  :data-debug="`subsub:${currentIndex[0]}-${currentIndex[1]}-${currentIndex[2]}|${typeIdx}-${itemIdx}-${subIdx}`"
                  @click="selectRow(typeIdx,itemIdx,subIdx)"
                  @mouseenter="hoverIndex = typeIdx+'-'+itemIdx+'-'+subIdx"
                  @mouseleave="hoverIndex = ''">
                  <td style="text-align: center;width: 70px;">{{ typeIdx + 1 }}.{{ itemIdx + 1 }}.{{ subIdx + 1 }}</td>
                  <td style="padding-left: 50px;">{{ subItem.title }}</td>
                  <td style="text-align: center;width: 93px;">
                    {{ getSelectedScore(subItem.options) || subItem.score || '' }}
                  </td>
                </tr>
              </template>
            </template>
            <!-- 没有第三级子题的情况（原来的二级题目） -->
            <tr v-else-if="item.title"
              :class="{
                selected: selectedIndex === typeIdx+'-'+itemIdx,
                hovered: hoverIndex === typeIdx+'-'+itemIdx,
                current: currentIndex[0] === typeIdx && currentIndex[1] === itemIdx
              }"
              :data-debug="`sub:${currentIndex[0]}-${currentIndex[1]}|${typeIdx}-${itemIdx}`"
              @click="selectRow(typeIdx,itemIdx,undefined)"
              @mouseenter="hoverIndex = typeIdx+'-'+itemIdx"
              @mouseleave="hoverIndex = ''">
            <td style="text-align: center;width: 70px;">{{ typeIdx + 1 }}.{{ itemIdx + 1 }}</td>
            <td style="padding-left: 30px;">{{ item.title }}</td>
            <td style="text-align: center;width: 93px;">
              {{ getSelectedScore(item.options) || item.score || '' }}
            </td>
          </tr>
          </template>
        </template>
      </tbody>
    </table>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from 'vue'

// 翻译系统
const translationVersion = ref(0)
let t = (key: any, params?: any) => {
	const keys = key.split('.')
	let current: any = translations.value
	for (const k of keys) {
		if (current && typeof current === 'object') {
			current = current[k]
		} else {
			return key
		}
	}
	if (typeof current === 'string' && params) {
		return current.replace(/\{(\w+)\}/g, (match: any, key: any) => params[key] || match)
	}
	return current || key
}

const translations = ref<any>({})

async function initTranslations() {
	try {
		const currentLang = localStorage.getItem('language') || 'zh-CN'
		let langModule
		if (currentLang === 'en-US') {
			langModule = await import('../../../i18n/locales/en-US')
		} else {
			langModule = await import('../../../i18n/locales/zh-CN')
		}
		translations.value = langModule.default
		translationVersion.value++
	} catch (error) {
		console.error('Failed to load translations:', error)
	}
}

// 获取选中选项的分数显示（支持数值和字母等级）
const getSelectedScore = (options: any[]) => {
  if (!options || !options.length) return '';
  
  const selectedOptions = options.filter((o: any) => o.isSelected);
  if (!selectedOptions.length) return '';
  
  // 如果只有一个选中项，直接返回其分数
  if (selectedOptions.length === 1) {
    return selectedOptions[0].score || '';
  }
  
  // 多个选中项的情况
  const scores = selectedOptions.map((o: any) => o.score);
  
  // 检查是否都是数值
  const allNumbers = scores.every((score: any) => !isNaN(Number(score)) && score !== '');
  
  if (allNumbers) {
    // 如果都是数值，进行累加
    return scores.reduce((sum: number, score: any) => sum + (Number(score) || 0), 0);
  } else {
    // 如果包含字母等级，用逗号连接
    return scores.filter((score: any) => score !== '').join(', ');
  }
}

// 计算二级题目总分（有第三级子题的情况）
const getSubTypeScore = (item: any) => {
  if (!item.questionList || !item.questionList.length) {
    return getSelectedScore(item.options) || item.score || '';
  }
  
  let total = 0;
  let hasNumericScore = false;
  
  item.questionList.forEach((subItem: any) => {
    if (subItem.options && subItem.options.length > 0) {
      const selectedOptions = subItem.options.filter((option: any) => option.isSelected);
      selectedOptions.forEach((option: any) => {
        const score = Number(option.score);
        if (!isNaN(score)) {
          total += score;
          hasNumericScore = true;
        }
      });
    }
  });
  
  return hasNumericScore ? total : '';
}

// 计算大题总分（支持三级结构）
const getTypeScore = (type: any) => {
  if (!type.questionList || !type.questionList.length) {
    // 如果没有子题，显示大题本身的分数
    return getSelectedScore(type.options) || type.score || '';
  }
  
  // 有子题的情况，计算所有子题的数值分数总和
  let total = 0;
  let hasNumericScore = false;
  
  type.questionList.forEach((question: any) => {
    // 如果有第三级子题
    if (question.questionList && question.questionList.length > 0) {
      question.questionList.forEach((subQuestion: any) => {
        if (subQuestion.options && subQuestion.options.length > 0) {
          const selectedOptions = subQuestion.options.filter((option: any) => option.isSelected);
          selectedOptions.forEach((option: any) => {
            const score = Number(option.score);
            if (!isNaN(score)) {
              total += score;
              hasNumericScore = true;
            }
          });
        }
      });
    } else if (question.options && question.options.length > 0) {
      // 没有第三级子题的情况
      const selectedOptions = question.options.filter((option: any) => option.isSelected);
      selectedOptions.forEach((option: any) => {
        const score = Number(option.score);
        if (!isNaN(score)) {
          total += score;
          hasNumericScore = true;
        }
      });
    }
  });
  
  return hasNumericScore ? total : '';
}

const emit = defineEmits(['selectRow'])
const props = defineProps({
    infoData: {
      type: Object,
    required: false,
      default: () => ({})
  },
  currentIndex: {
    type: Array,
    required: false,
    default: () => [0,-1,-1]
  }
})

const selectedIndex = ref<string>('')
const hoverIndex = ref<string>('')

// 监听currentIndex变化，自动滚动到当前行
watch(() => props.currentIndex, (newIndex) => {
  if (!newIndex || newIndex.length === 0) return
  
  nextTick(() => {
    // 根据currentIndex找到对应的行并滚动
    const [typeIdx, itemIdx, subIdx] = newIndex
    let targetSelector = ''
    
    if (itemIdx === -1) {
      // 一级大题
      targetSelector = `.current[data-debug*="main:${typeIdx}-${itemIdx}|${typeIdx}"]`
    } else if (subIdx === -1 || subIdx === undefined) {
      // 二级题目
      targetSelector = `.current[data-debug*="sub:${typeIdx}-${itemIdx}"]`
    } else {
      // 三级子题
      targetSelector = `.current[data-debug*="subsub:${typeIdx}-${itemIdx}-${subIdx}|${typeIdx}-${itemIdx}-${subIdx}"]`
    }
    
    const targetElement = document.querySelector(targetSelector)
    if (targetElement) {
      targetElement.scrollIntoView({
        behavior: 'auto',
        block: 'center'
      })
    }
  })
}, { immediate: true, deep: true })

function selectRow(idx: any,itemIdx: any, subIdx?: any) {
  console.log(idx, itemIdx, subIdx)
  if (itemIdx === undefined) { 
    itemIdx=-1
  }
  if (subIdx === undefined) {
    subIdx = -1
  }
  emit('selectRow',Number(idx),Number(itemIdx),Number(subIdx))
  
  // 更新selectedIndex
  if (itemIdx === -1) {
    selectedIndex.value = String(idx)
  } else if (subIdx === -1) {
    selectedIndex.value = `${idx}-${itemIdx}`
  } else {
    selectedIndex.value = `${idx}-${itemIdx}-${subIdx}`
  }
}

onMounted(async () => {
	// 初始化翻译
	await initTranslations()
})
</script>
<style scoped>
.qus-table-container {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(21,138,192,0.08);
  height: 60vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.qus-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  flex: 1;
  color: #333;
  font-weight: bold;
  display: block;
}
.qus-table thead {
  position: sticky;
  top: 0;
  z-index: 1;
  background: #fff;
  display: table;
  width: 100%;
}
.qus-table tbody {
  display: block;
  width: 100%;
  height: calc(63vh - 100px);
  overflow-y: auto;
}
.qus-table tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
}

.qus-table::-webkit-scrollbar {
  width: 6px;
  background: transparent;
}

.qus-table::-webkit-scrollbar-thumb {
  background: var(--theme-primary);
  border-radius: 3px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.qus-table::-webkit-scrollbar-track {
  background: transparent;
}

.qus-table th {
  background: var(--theme-primary);
  color: #fff;
  font-weight: bold;
  padding: 10px 0;
  position: sticky;
  top: 0;
  text-align: left;
}

.qus-table td {
  padding: 10px 0;
  text-align: left;
  border-right: 1px solid #fff;
  border-bottom: 1px solid #f0f0f0;
  transition: background 0.2s, box-shadow 0.2s, border 0.2s;
  background: transparent;
}

.qus-table tr:nth-child(even) td {
  background: #ececec;
}

.qus-table tr.selected td {
  background: var(--theme-secondary-light) !important;
}

.qus-table tr.hovered td {
  background: var(--theme-secondary-light) !important;

  /* box-shadow: 0 0 0 2px #ffd600 inset; */
}

.qus-table tr.current td {
  background: var(--theme-secondary) !important;
}

/* 圆角处理 */
.qus-table tr:first-child th:first-child {
  border-top-left-radius: 12px;
}
.qus-table tr:first-child th:last-child {
  border-top-right-radius: 12px;
}
.qus-table tr:last-child td:first-child {
  border-bottom-left-radius: 12px;
}
.qus-table tr:last-child td:last-child {
  border-bottom-right-radius: 12px;
}

.qus-table tbody::-webkit-scrollbar {
  width: 6px;
  background: transparent;
}
.qus-table tbody::-webkit-scrollbar-thumb {
  background: var(--theme-primary);
  border-radius: 3px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}
.qus-table tbody::-webkit-scrollbar-track {
  background: transparent;
}
</style>